package com.china08.yxyapi.api.manage.tec.teaching.scoreport.updateexam;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.entity.mg.scoreport.Exam;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.repository.mg.scoreport.ExamRepository;
import com.china08.yxyapi.util.DateUtils;

/**
 * 导入成绩信息后修改数据
 * 
 */
@CrossOrigin
@RestController
public class UpdateExamController {

    @Autowired
    ExamRepository examRepository;

    @RequestMapping(value = "/api_yw/manage/tec/teaching/scoreport/updateexam/update", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void process(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel model)
            throws ParseException {
        model.check();
        Exam exam = examRepository.findOne(model.id);
        if (null != exam) {
            exam.setName(model.name);
            exam.setType(model.type);
            exam.setExamDate(DateUtils.formatDate4(DateUtils.formatStrDate3(model.examDate.replace("-", ""))));
            List<Exam.BookContent> list = new ArrayList<Exam.BookContent>();
            for (BookContent bc : model.bookContents) {
                Exam.BookContent bookContent = exam.new BookContent();
                bookContent.id = bc.id;
                bookContent.pid = bc.pid;
                bookContent.name = bc.name;
                list.add(bookContent);
            }
            exam.setBookContents(list);
            examRepository.save(exam);
        }
    }

    /**
     * 请求参数
     * 
     */
    protected static class ReqModel extends YxyApiReqModel {
        // 考试id
        public String id;
        // 考试名称
        public String name;
        // 考试类型
        public String type;
        // 考试时间
        public String examDate;
        // 考试涉及知识点
        public List<BookContent> bookContents;

        public void check() {
            Assert.notNull(StringUtils.defaultIfBlank(id, null), "考试编号不能为空");
        }
    }

    public static class BookContent {
        public String pid;
        public String id;
        public String name;
    }
}
